package cn.lyjuan.citycode.pinyin.dao;

import bean.CityCodeBean;
import cn.lyjuan.base.util.MySQL;
import cn.lyjuan.base.util.ProxoolDBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class CityCodeDao
{
    public static List<CityCodeBean> select()
    {
        return MySQL.getInstance().select(CityCodeBean.class);
    }

    public static int updatePinyin(List<CityCodeBean> list)
    {
        int count = -1;
        Connection conn = ProxoolDBUtils.getConn();
        PreparedStatement ps = null;

        String sql = "update " + CityCodeBean.TABLE_NAME + " set pinyin=?, pinyin_simple=? where id = ?";
        try
        {
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
        } catch (SQLException e)
        {
            ProxoolDBUtils.close(null, ps, conn);
            throw new RuntimeException(e);
        }

        try
        {
            for (int i = 0; i < list.size(); i++)
            {
                CityCodeBean c = list.get(i);
                ps.setString(1, c.getPinyin());
                ps.setString(2, c.getPinyin_simple());
                ps.setInt(3, c.getId());
                ps.addBatch();

                if (i > 0 && i % 500 == 0)
                    ps.executeBatch();
            }

            ps.executeBatch();

            ProxoolDBUtils.commit(conn);
        } catch (SQLException e)
        {
            throw new RuntimeException(e);
        } finally
        {
            ProxoolDBUtils.close(null, ps, conn);
        }
        return count;
    }
}
